package miniprogram

import (
	"fmt"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

// MpSession 小程序 token
type MpSession struct {

	// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

	Ctx iris.Context
}

func (c *MpSession) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("GET", "/mp/s1", "GetPing")
}

func (c *MpSession) GetPing() string {
	c.Ctx.Application().Logger().Infof("abcdefg!!!!")

	c.Ctx.PostValues("1ab")
	return "pong"
}

func (c *MpSession) GetSession() {
	api := NewAPI()
	code := c.Ctx.URLParam("code")
	fmt.Println("code=", code)
	res := api.JSCode2Session(code)

	c.Ctx.JSON(iris.Map{"flag": res.Success, "msg": res.Message, "data": res.Response})
}

func (c *MpSession) PostLogin() {
	mobile := c.Ctx.FormValue("mobile")
	smsvcode := c.Ctx.FormValue("smsvcode")
	openid := c.Ctx.FormValue("openid")

	fmt.Println("mobile=", mobile)

	if len(mobile) != 11 {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "手机号码有误", "data": nil})
		return
	}

	if len(smsvcode) != 4 {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "验证码有误", "data": nil})
		return
	}

	if len(openid) == 0 {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "参数openid值为空", "data": nil})
		return
	}

	// 假设登录成功
	data := iris.Map{"access_token": "123dk31-adfe123kdsfefkadfe-ef"}

	c.Ctx.JSON(iris.Map{"flag": true, "msg": "", "data": data})
	return
}
